package com.three.server.oss;


import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.OSSObject;
import com.smartcar.common.constants.OssConstant;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class FileDownloader {
    // 配置您的OSS访问信息
    String endpoint = OssConstant.ENDPOINT;
    String accessKeyId = OssConstant.ACCESS_KEY_ID;
    String accessKeySecret = OssConstant.ACCESS_KEY_SECRET;
    String bucketName = OssConstant.BUCKET_NAME;

    public void downLoadByOSS(String objectName, String localFilePath) {
        // 创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // 下载文件到本地
            GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, objectName);
            OSSObject ossObject = ossClient.getObject(getObjectRequest);
            InputStream inputStream = ossObject.getObjectContent();

            File localFile = new File(localFilePath);
            FileOutputStream outputStream = new FileOutputStream(localFile);

            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }

            System.out.println("文件下载成功，保存路径：" + localFile.getAbsolutePath());


            // 关闭流
            outputStream.close();
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭OSSClient
            ossClient.shutdown();
        }

    }


}
